package com.thx.web.filter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.thx.common.spring.BeanFactory;
import com.thx.common.util.AppContext;
import com.thx.common.web.WebConstant;
import com.thx.common.web.filter.SessionFilter;
import com.thx.privilege.PriviManager;
import com.thx.privilege.PriviManagerFactory;
import com.thx.privilege.PriviObj;
import com.thx.resource.model.Resource;
import com.thx.resource.service.ResourceManager;
import com.thx.role.model.Role;
import com.thx.role.service.RoleManager;
import com.thx.user.model.User;

/**
 * 建立日期 : Jul 29, 2012 2:45:09 PM<br>
 * 作者 : 贾红磊<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
public class WebSessionFilter extends SessionFilter {

  @Override
  protected boolean checkSession(HttpSession session, HttpServletRequest request,
      HttpServletResponse response) {
    Object user = session.getAttribute(WebConstant.KEY_USER);
    if (user != null) {
      User u = (User) user;
      AppContext.setCurrentComId(u.getComId());
      return true;
    } else
      return false;
  }

  @Override
  protected boolean checkPrivilege(HttpSession session, HttpServletRequest request,
      HttpServletResponse response) {
    boolean result = false;
    String servletPath = request.getServletPath();
    ResourceManager resourceManager = (ResourceManager) BeanFactory.getBean("resourceManager");
    Resource resource = resourceManager.findByUrl(servletPath.substring(1));
    if (resource == null) {
      String config = AppContext.getProperties("exculdeOfResouce");
      if (StringUtils.isBlank(config)) {
        result = true;
      } else {
        result = Boolean.parseBoolean(config);
      }
    } else {
      User user = (User) session.getAttribute(WebConstant.KEY_USER);
      if (user != null) {
        PriviManager priviManager = PriviManagerFactory.getpPriviManager();
        result =
            priviManager.hasUserPrivi(user.getUserId(), resource.getResourceId(),
                PriviObj.PRIVITYPE_MENU);
        if (result)
          return result;
        List<Role> roleList = user.getRoleList();
        if (roleList == null) {
          roleList = ((RoleManager) BeanFactory.getBean("roleManager")).findByUserId(user.getUserId());
          if(roleList==null)roleList=new ArrayList<Role>();
          user.setRoleList(roleList);
        }

        Iterator<Role> it = roleList.iterator();
        while (it.hasNext() && !result) {
          Role role = it.next();
          result = priviManager.hasRolePrivi(role.getRoleId(), resource.getResourceId(), PriviObj.PRIVITYPE_MENU);
        }
      }
    }
    return result;
  }
}
